package com.xiaoxing.yunshu.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xiaoxing.yunshu.R;
import com.xiaoxing.yunshu.di.component.DaggerLoginComponent;
import com.xiaoxing.yunshu.di.module.LoginModule;
import com.xiaoxing.yunshu.mvp.contract.LoginContract;
import com.xiaoxing.yunshu.mvp.presenter.LoginPresenter;
import com.xiaoxing.yunshu.mvp.ui.entity.Login;
import com.xw.repo.XEditText;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.NetworkUtil;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.APP_LOGIN_ACTIVITY)
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View, EasyPermissions.PermissionCallbacks {

    private static final int LOGIN_SUCCESS = 0;
    private static final int USER_PASSWORD_ERRO = 1;
    private static final int NETWORK_ERROR = 2;
    private static final int SYS_ERROR = 3;

    @BindView(R.id.xet_username)
    XEditText xetUsername;
    @BindView(R.id.xet_password)
    XEditText xetPassword;
    @BindView(R.id.cb_ji_zhu_mi_ma)
    CheckBox cbJiZhuMiMa;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.btn_she_zhi)
    Button btnSheZhi;
    @BindView(R.id.radioButton_driver)
    RadioButton radioButtonDriver;
    @BindView(R.id.radioButton_receiver)
    RadioButton radioButtonReceiver;
    @BindView(R.id.radioGroup_career)
    RadioGroup radioGroupCareer;

    private String orders;

    private String[] permissionsLocation = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION,
//            Manifest.permission.FOREGROUND_SERVICE,
//            Manifest.permission.ACCESS_BACKGROUND_LOCATION
    };
    private String[] permissionsLocation1 = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
//            Manifest.permission.FOREGROUND_SERVICE,
//            Manifest.permission.ACCESS_BACKGROUND_LOCATION
    };
    private boolean isOrdersDriver = false;


    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
        ARouter.getInstance().inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_login; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
//
//        if (TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_IP)) || TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_PORT))) {
//            Utils.navigation(LoginActivity.this, RouterHub.APP_SHE_ZHI_ACTIVITY);
//            return;
//        }
        if (!TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.USERNAME)) && !TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.PASSWORD))) {
            xetUsername.setText(mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
            xetPassword.setText(mSharedPreferencesHelper.getString(BaseConstants.PASSWORD));
        }
//        mSharedPreferencesHelper.putString(BaseConstants.SHE_ZHI_IP, BaseConstants.SHE_ZHI_IP_VALUE);
//        mSharedPreferencesHelper.putString(BaseConstants.SHE_ZHI_PORT, BaseConstants.SHE_ZHI_PORT_VALUE);

//        ToolbarUtils.initToolbarTitleNoBack(this, getString(R.string.login_deng_lu));
        if (mSharedPreferencesHelper.getBoolean(BaseConstants.JI_ZHU_MI_MA)) {
            cbJiZhuMiMa.setChecked(true);
        }
//        autoLogin();

    }

    @Override
    protected void onResume() {
        super.onResume();

//        if (!TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_IP)) && !TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_PORT))) {
//            RetrofitUrlManager.getInstance().setGlobalDomain(getUrl());
//        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

        if (requestCode == 104) {

        }
    }

    /**
     * 自动登陆
     */
    public void autoLogin() {
        if (NetworkUtil.checkNetworkAvailable(this)) {

            String username = mSharedPreferencesHelper.getString(BaseConstants.USERNAME);
            String pwd = mSharedPreferencesHelper.getString(BaseConstants.PASSWORD);
            if (username != null && pwd != null) {
                xetUsername.setText(username);
                if (jiZhuMiMaIsChecked()) {
                    xetPassword.setText(pwd);
//                    login();
                }

            }
        }
    }

    private boolean jiZhuMiMaIsChecked() {
        return cbJiZhuMiMa.isChecked();
    }

    @OnClick({R.id.cb_ji_zhu_mi_ma, R.id.btn_login, R.id.btn_she_zhi, R.id.tv_forgot_pwd, R.id.tv_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_forgot_pwd:
                Utils.navigation(LoginActivity.this, RouterHub.ACTIVITY_FORGOT_PWD);
                break;
            case R.id.tv_register:
                Utils.navigation(LoginActivity.this, RouterHub.ACTIVITY_REGISTER);
                break;
            case R.id.cb_ji_zhu_mi_ma:
                jiZhuMiMa();
                break;
            case R.id.btn_login:
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    if (getLocationPermission()) {
                        login();
                    }

                } else {
                    if (getLocationPermission1()) {
                        login();
                    }

                }


                break;
            case R.id.btn_she_zhi:
                toSheZhiActivity();
//                addressChangeLat();
                break;
        }
    }

    /**
     * 点击记住密码Checkbox
     */
    private void jiZhuMiMa() {
        if (jiZhuMiMaIsChecked()) {
            mSharedPreferencesHelper.putBoolean(BaseConstants.JI_ZHU_MI_MA, true);
        } else {
            mSharedPreferencesHelper.putBoolean(BaseConstants.JI_ZHU_MI_MA, false);
        }
    }

    private boolean getLocationPermission() {
        if (EasyPermissions.hasPermissions(this, permissionsLocation)) {

            return true;
        } else {

            EasyPermissions.requestPermissions(this, "需要获取相关权限", 104, permissionsLocation);
            return false;
        }

    }

    /**
     * 点击登录
     */
    private void login() {
//        String sheZhiIP = mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_IP);
//        String sheZhiPORT = mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_PORT);
//
//        if (TextUtils.isEmpty(sheZhiIP) || TextUtils.isEmpty(sheZhiPORT)) {
//            ArmsUtils.makeText(this, getString(R.string.qing_xian_she_zhi_ip_port));
//            toSheZhiActivity();
//            return;
//        }

        if (TextUtils.isEmpty(getUsername())) {
            ArmsUtils.makeText(this, getString(R.string.zhang_hao_bu_neng_wei_kong));
            return;
        }

        if (TextUtils.isEmpty(getPassword())) {
            ArmsUtils.makeText(this, getString(R.string.mi_ma_bu_neng_wei_kong));
            return;
        }

        mSharedPreferencesHelper.putString(BaseConstants.USERNAME, getUsername());
        if (jiZhuMiMaIsChecked()) {
            mSharedPreferencesHelper.putBoolean(BaseConstants.JI_ZHU_MI_MA, true);
            mSharedPreferencesHelper.putString(BaseConstants.PASSWORD, getPassword());
        }
        mPresenter.login(getUsername(), getPassword());
//        callWebService();
    }

    private boolean getLocationPermission1() {
        if (EasyPermissions.hasPermissions(this, permissionsLocation1)) {

            return true;
        } else {

            EasyPermissions.requestPermissions(this, "需要获取相关权限", 104, permissionsLocation1);
            return false;
        }

    }

    /**
     * 跳转到设置页面
     */
    private void toSheZhiActivity() {
        Utils.navigation(LoginActivity.this, RouterHub.APP_SHE_ZHI_ACTIVITY);
    }

    @NonNull
    private String getUsername() {
        return xetUsername.getText().toString();
    }

    @NonNull
    private String getPassword() {
        return xetPassword.getText().toString();
    }


    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this, "登录中...");
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @Override
    public void loginSuccessed(Login login) {

        try {
            showMessage(login.getMessage());
            if (login.getCode() == 200) {
                Login.DataBean dataBean = login.getData();
                mSharedPreferencesHelper.putString(BaseConstants.UID, String.valueOf(dataBean.getID()));
                mSharedPreferencesHelper.putString(BaseConstants.COMPANY, dataBean.getName());
                mSharedPreferencesHelper.putString(BaseConstants.DISPLAY_NAME, dataBean.getName());
                mSharedPreferencesHelper.putString(BaseConstants.MOBILE_PHONE, dataBean.getMobilePhone());

                mSharedPreferencesHelper.putString(BaseConstants.NAME, dataBean.getName());
                mSharedPreferencesHelper.putString(BaseConstants.CARD_NO, dataBean.getDriver().getIDCardNo());
                mSharedPreferencesHelper.putString(BaseConstants.BIRTH, dataBean.getDriver().getBirthday());
                mSharedPreferencesHelper.putString(BaseConstants.SEX, dataBean.getDriver().getSex());
                mSharedPreferencesHelper.putString(BaseConstants.DRIVING_AGE, dataBean.getDriver().getDrivingAge());

                mSharedPreferencesHelper.putString(BaseConstants.USERNAME_AUTHORIZATION, dataBean.getLoginName());
                mSharedPreferencesHelper.putString(BaseConstants.PASSWORD_AUTHORIZATION, getPassword());


                Utils.navigation(this, RouterHub.APP_MAIN_ACTIVITY);
                killMyself();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


}
